"use strict"

const redis = require('redis').createClient()
const _ = require('lodash/fp')
const mysql = require('mysql2/promise')
const config = require('../config')
const myStore = require('./index.js')

redis.on('error', console.log)

const numWorld2int = num => isNaN(parseInt(num)) ? 0 : /万/.test(num) ? parseFloat(num) * 10000 : parseInt(num)

const getCateMap = async () => {
    const db = await mysql.createConnection(config.DB)
    const cates = await db.query(`SELECT cate_id FROM qyg_category WHERE cate_pid = 47`).then(rows => _.map('cate_id', rows[0]))
    const live_cate_map = await db.query(`SELECT id, CONCAT(\`live_id\`, '.', \`cid\`) as name FROM qyg_live_categories`)
        .then(t => {
            const map = {}
            _(t[0]).each(t => map[t.id] = t.name)
            return map
        })
    const live_cates = await db.query(`SELECT * FROM qyg_cate_live_cate`).then(t => _(t[0]))
    const cate_map = {}
    _(cates).each(t => {
        cate_map[t] = live_cates.filter(_ => _.cid == t).map('live_cid').map(t => live_cate_map[t]).value()
    })
    db.end()
    return [cates, cate_map]
}

const store = async data => {
    myStore(data)
    const [cates, cate_map] = await getCateMap()
    redis.del(cates.map(_ => `zLives.${_}`).concat('zOnline', 'hLives'))
    _(data).chunk(1000).each(c => {
        const set = ['zOnline']
        _(c).each(t => {
            const key = `${t.live_id}.${t.category_id}`
            t.online = numWorld2int(t.online)
            for (let cate in cate_map) {
                if (cate_map[cate].includes(key)) {
                    redis.zadd(`zLives.${cate}`, t.online, t.id)
                    break
                }
            }
            redis.hset(`hLives`, t.id, JSON.stringify(t))
            set.push(t.online, t.id)
        })
        redis.zadd(set)
    })

    redis.quit()
}

module.exports = store